package com.dubbo.soa.spring.parse;

import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.beans.factory.xml.BeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext;
import org.w3c.dom.Element;

public class ProtocolBeanDefinitionParse implements BeanDefinitionParser {
    private Class<?> beanClass;
    public ProtocolBeanDefinitionParse(Class<?> beanClass){
        this.beanClass = beanClass;
    }
    public BeanDefinition parse(Element element, ParserContext parserContext) {
        //element对象传到reference，并交由spring管理
        RootBeanDefinition rootBeanDefinition = new RootBeanDefinition();
        rootBeanDefinition.setBeanClass(beanClass);
        rootBeanDefinition.setLazyInit(false);
        String id = element.getAttribute("id");
        String name = element.getAttribute("name");
        String port = element.getAttribute("port");
        String host = element.getAttribute("host");
        if(id != null && !"".equals(id)){
            if(parserContext.getRegistry().containsBeanDefinition(id)){
                throw new IllegalStateException("id不能为空，参照标准（<sunne:protocol id=\"zdysoakjxy\" name=\"http\" host=\"127.0.0.1\" port=\"8083\"></sunne:protocol>）");
            }
            rootBeanDefinition.getPropertyValues().add("id",id);
        }else {
            //假如id没有配置，id生成策略
            id = beanClass.getName().substring(0,1).toLowerCase()+
                    beanClass.getName().substring(1);
            rootBeanDefinition.getPropertyValues().add("id",id);


        }
        if (name == null || "".equals(name)){
            throw new IllegalStateException("协议名不能为空，参照标准（<sunne:protocol id=\"zdysoakjxy\" name=\"http\" host=\"127.0.0.1\" port=\"8083\"></sunne:protocol>）");
        }else {
            rootBeanDefinition.getPropertyValues().add("name",name);
        };
        if(port == null || "".equals(port)){
            throw new IllegalStateException("端口不能为空，参照标准（<sunne:protocol id=\"zdysoakjxy\" name=\"http\" host=\"127.0.0.1\" port=\"8083\"></sunne:protocol>）");
        }else{
            rootBeanDefinition.getPropertyValues().add("port",port);
        }
        if(host == null || "".equals(host)){
            throw new IllegalStateException("地址不能为空，参照标准（<sunne:protocol id=\"zdysoakjxy\" name=\"http\" host=\"127.0.0.1\" port=\"8083\"></sunne:protocol>）");
        }else{
            rootBeanDefinition.getPropertyValues().add("host",host);
        }
        //创建出来的rootBeanDefinition必须交由spring管理
        parserContext.getRegistry().registerBeanDefinition(id,rootBeanDefinition);
        return rootBeanDefinition;
    }
}
